package com.hosever.core.web.annotation;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.hosever.core.model.PageRequest;

/**
 * control类的PageRequest参数构造
 * 
 * @author hosever
 */
public class PageRequestMethodArgumentResolver implements
		HandlerMethodArgumentResolver {
	
	private static final String PAGE_NUMBER_PARAMETER_NAME = "pageNumber";
	
	private static final String PAGE_SIZE_PARAMETER_NAME = "pageSize";

	// 分页的默认size为 10
	private static final int PAGE_SIZE = 10;
	
	// 分页的默认最大size为 1000
	private static final int MAX_PAGE_SIZE = 1000;

	private static PageRequest createPageRequest(NativeWebRequest webRequest) {
		int pageNumber = getNumber(webRequest, PAGE_NUMBER_PARAMETER_NAME, 1);
		int pageSize = getNumber(webRequest, PAGE_SIZE_PARAMETER_NAME, 10);
		if(pageSize <=0)
			pageSize = PAGE_SIZE;
		if(pageSize > MAX_PAGE_SIZE)
			pageSize = MAX_PAGE_SIZE;
		
		PageRequest pageRequest = new PageRequest();
		pageRequest.setCurrentPage(pageNumber);
		pageRequest.setPageSize(pageSize);
		return pageRequest;
	}
	
	private static int getNumber(NativeWebRequest webRequest, String parameterName, int defaultValue) {
		try {
			String parameterValue = webRequest.getParameter(parameterName);
			return Integer.valueOf(parameterValue);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		Class<?> paramType = parameter.getParameterType();
		if (PageRequest.class.isAssignableFrom(paramType)) {
			return createPageRequest(webRequest);
		}
		return null; 
	}
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		Class<?> paramType = parameter.getParameterType();
		return PageRequest.class.isAssignableFrom(paramType);//判断一个类Class1和另一个类Class2是否相同或是另一个类的子类或接口
	}
}
